<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" :icon="Plus" plain @click="handleAdd">新增</el-button>
          </el-col>

          <!-- <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar> -->
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="权限名称" prop="permissionsName" :show-overflow-tooltip="true" />
        <el-table-column label="权限描述" prop="detailsDescribe" :show-overflow-tooltip="true" />
        <el-table-column label="更新者" prop="createUserName" :show-overflow-tooltip="true" />
        <el-table-column label="更新时间" prop="createTime" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <div v-if="scope.row.cannotDelete != 'true'">
              <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)" />
              <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="data.queryParams.total > 0" v-model:page="data.queryParams.pageNum"
        v-model:limit="data.queryParams.pageSize" :total="data.queryParams.total" @pagination="getList" />

    </el-card>
    <el-dialog v-model="dialogVisible" :title="actionType === 'add' ? '新增' : '修改'" width="500"
      :before-close="handleClose">
      <el-form :model="addForm" ref="ruleFormRef" label-width="106px" :rules="rules">
        <el-form-item label="权限名称" label-width="80px" prop="permissionsName">
          <el-input v-model="addForm.permissionsName" autocomplete="off" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="权限描述" label-width="80px" prop="detailsDescribe">
          <el-input v-model="addForm.detailsDescribe" type="textarea" :rows="5" placeholder="请输入权限描述">
          </el-input>
        </el-form-item>
        <div class="form_permission_box">
          <div class="box_header">
            <span class="header_text">权限配置</span>
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
              全选 </el-checkbox>
          </div>
          <div class="perm_box">
            <el-checkbox-group v-model="addForm.detailsIds" @change="handleCheckedTransport">
              <el-checkbox v-for="(item, index) in permissionsList" :label="item.detailsId" :key="index"
                :value="item.detailsId">
                {{ item.detailsName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <el-form-item>

          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  apiSysSchedulePermissionsGetAll,
  apiSysSchedulePermissionsGetRelevance,
  apiSysSchedulePermissionsAdd,
  apiSysSchedulePermissionsEditId,
  apiSysSchedulePermissionsEdit,
  apiSysSchedulePermissionsDelete
} from "@/api/resources/calendarManagementApi"
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance

const loading = ref(true)
const showSearch = ref(true)
const dataList = ref([])
const selectionList = ref([])
const dialogVisible = ref(false)
const actionType = ref('add')
const ruleFormRef = ref<FormInstance>()
const addForm = reactive({
  permissionsId: '',

  permissionsName: '',
  detailsDescribe: "",
  detailsIds: []
})
const permissionsList = ref([])
const checkAll = ref(false)
const isIndeterminate = ref(false)


const rules = reactive<FormRules>({
  permissionsName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
  ],
  detailsDescribe: [
    { required: true, message: '请输入权限描述', trigger: 'blur' },
  ]

})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    realName: '',
  },
})



/**
 * 查询模板列表
 */
const getList = async () => {
  loading.value = true
  const res: any = await apiSysSchedulePermissionsGetAll({
    pageNum: data.queryParams.pageNum,
    pageSize: data.queryParams.pageSize,

  })
  if (res.code == 200) {
    loading.value = false
    dataList.value = res.data
    // data.queryParams.total = res.data.total
  }
}

// 获取权限列表
const getPermissionsList = async () => {
  const res = await apiSysSchedulePermissionsGetRelevance()
  permissionsList.value = res.data
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  data.queryParams.pageNum = 1
  getList()
}

/** 重置 */
const resetQuery = () => {
  // dateRange.value = ['', ''];
  // queryFormRef.value?.resetFields();
  // handleQuery();
}
const handleSelectionChange = (val) => {
  selectionList.value = val
}
const handleAdd = () => {
  dialogVisible.value = true
  actionType.value = 'add'
  addForm.permissionsName = ''
  addForm.detailsDescribe = ''
  addForm.detailsIds = []
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (actionType.value == 'add') {
        addFormData()
      } else {
        editFormData()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const addFormData = async () => {
  const res = await apiSysSchedulePermissionsAdd({
    ...addForm
  })
  if (res.code == 200) {
    ElMessage.success('添加成功')
  } else {
    ElMessage.error(res.msg)
  }
  handleClose()
  getList()
}
const handleEdit = async (row) => {
  console.log(row)
  actionType.value = 'edit'
  const res = await apiSysSchedulePermissionsEditId(row.permissionsId)
  if (res.code == 200) {
    addForm.permissionsId = res.data.permissionsId
    addForm.permissionsName = res.data.permissionsName
    addForm.detailsDescribe = res.data.detailsDescribe
    let ids = res.data.sysScheduleDetailsList.map((item) => item.detailsId)
    addForm.detailsIds = ids
    dialogVisible.value = true
    handleCheckedTransport(ids)
  }
}
const editFormData = async () => {
  const res = await apiSysSchedulePermissionsEdit(addForm)
  if (res.code == 200) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(res.msg)
  }
  getList()
  handleClose()
}
const handleCheckedTransport = (value) => {
  let checkedCount = value.length
  checkAll.value = checkedCount === permissionsList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < permissionsList.value.length
}
const handleClose = () => {
  dialogVisible.value = false
  ruleFormRef.value?.resetFields()
  addForm.detailsIds = []
  // isIndeterminate.value = false
  checkAll.value = false
}
/**删除按钮操作 */
const handleDelete = async (item) => {
  ElMessageBox.confirm('此操作将永久删除该模板, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const ids = selectionList.value.map((item) => item.id)
    const res = await apiSysSchedulePermissionsDelete(item.permissionsId)
    if (res.code == 200) {
      ElMessage.success('删除成功')
      getList()
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
// 全选按钮
const handleCheckAllChange = (val) => {
  const all = permissionsList.value.map((item) => {
    return item.detailsId
  })
  addForm.detailsIds = val ? all : []
  isIndeterminate.value = false
}


onMounted(() => {
  getList()
  getPermissionsList()
})
</script>


<style lang="scss" scoped>
.form_permission_box {
  margin-top: 20px;

  .box_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    .header_text {
      font-weight: 600;
      color: #606266;
      margin-left: 13px;
    }
  }

  .perm_box {
    padding: 12px;
    border: 1px solid #ebeef5;

    :deep(.el-checkbox) {
      margin: 8px 15px 8px 0;
      width: 140px;
    }
  }
}
</style>